package com.browsesoft.user;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.ManagerGroup;
import com.browsesoft.SequenceFind;
import com.browsesoft.Tools;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLFormModel;
import com.browsesoft.resource.BasicResource;
import com.browsesoft.resource.Resource;

/**
 * 组织机构
 */
public class Organization extends BasicResource implements HTMLFormModel,
		Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 175392814369413236L;

	private transient Hashtable tempht = new Hashtable();

	private transient HTMLBasicComponent component = null;

	private String action = null;

	/**
	 * 默认构造函数
	 */
	public Organization() throws Exception {
		super();
	}

	public void setParentID(String parentID) {
		this.parentID = parentID;
	}
	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		parentID = request.getParameter("parentid");
		templateName = request.getParameter("templatename");
		this.setTemplateName(templateName);
		String id = request.getParameter("point");
		if (id != null && !id.equals("")) {
			// this.attributes = ( (Resource)
			// EntityManager.getObject(id)).getAttributes();
		}
	}

	/**
	 * 使用属性构造
	 */
	public Organization(Hashtable attrs) {
		super(attrs);
	}

	/**
	 * 更新组织属性
	 * 
	 */
	public void updateAttributes(Hashtable attrs) throws Exception {
		String name = (String) attrs.get("name");
		if (name != null) {
			if (!isSame(name)) {
				Element e = (Element) this.component.getPage().getDocument()
						.getElementsByTagName("body").item(0);
				e.setAttribute("onload", "wrongOrganizationMessageBox()");
			} else {
				Element e = (Element) this.component.getPage().getDocument()
						.getElementsByTagName("body").item(0);
				e.setAttribute("onload", "passwordupdate()");
				// 如果应该插入
				if (isShouldInsert()) {
					EntityManager entitymanager = (EntityManager) ManagerGroup
							.getManagerGroup().getManager("entity");
					// 放入图标
					this.attributes.put("f_icon", "tree_org");
					this.getAttributes().putAll(attrs);
					insert();
					Resource parent = (Resource) entitymanager
							.getObject(parentID);
					parent.addChild(this);
					parent.update();
					entitymanager.add(this);
					parentID = null;
				}
				this.attributes.putAll(attrs);
				this.attributes.putAll(tempht);
				// 如果应该更新数据库
				if (isShouldUpdate()) {
					this.update();
				}
			}
		}
	}

	/**
	 * 增加组织 (自己)
	 */
	public void insert(Organization org) throws Exception {
		Hashtable ht = new Hashtable();
		// 设置序列号
		String id = Integer.toString(SequenceFind.getID());
		ht.put("id", id);
		// 设置组织的所属父组织
		String parentid = this.getID();
		ht.put("parentid", parentid);
		// 增加属性
		org.getAttributes().putAll(ht);
		// 写库
		DBTools.insert("t_organization", org.getAttributes());
		// 在管理器中,父组织,组织列表 增加组织
		EntityManager entitymanager = (EntityManager) ManagerGroup
				.getManagerGroup().getManager("entity");
		this.addChild(org);
		entitymanager.add(org);
	}

	/**
	 * 记录客户端环境
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.action = request.getParameter("action");
		// 得到资源类型
		String rt = request.getParameter("resourcetype");
		if (rt == null || rt.equals("")) {
			tempht.put("resourcetype", "organization");
		} else {
			tempht.put("resourcetype", rt);
		}
	}

	/**
	 * 取得选项值列表
	 */
	public Iterator getOptions(String selectName) {
		return null;
	}

	/**
	 * 字符转换
	 * 
	 * @return
	 */
	public String toString() {
		// 根据属性名取得属性值
		return (String) this.getAttributes().get("name");
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	// 判断组织是否有相同名
	public boolean isSame(String name) throws Exception {
		EntityManager entitymanager = (EntityManager) ManagerGroup
				.getManagerGroup().getManager("entity");
		LinkedList v = new LinkedList();
		// 判断有无父组织
		if (parentID != null) {
			// 根据父ID取得父资源
			Resource p = (Resource) entitymanager.getObject(this.parentID);
			// 取出父的所有子
			v = Tools.iteratorToList(p.getChildren());
		}
		// 修改
		else {
			// 根据id取得资源
			Resource res = (Resource) entitymanager.getObject(this.getID());
			if (res.getParent() != null) {
				// 取出所有子
				v = Tools.iteratorToList(res.getParent().getChildren());
			}
			// 是根组织只能修改
			else {
				res = this;
				return true;
			}
		}
		// 查找组织名，有相同 的return false
		for (int i = 0; i < v.size(); i++) {
			// 判断每个子资源是否是组织
			if (v.get(i) instanceof Organization) {
				// 取出组织的名称
				String temp = (String) ((Organization) v.get(i))
						.getAttributes().get("name");
				// 判断是否有同名的组织
				if (!temp.equals((String) getAttributes().get("name"))) {
					if (name.equals(temp)) {
//						return false;
					}
				}
			}
		}
		return true;
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	public String getTableName() {
		return "t_organization";
	}

	/**
	 * 得到该资源下的所有子
	 * 
	 * @return Linkedlist
	 */
	/*
	 * public LinkedList getAllChildrens() { LinkedList childrenUsers = new
	 * LinkedList(); LinkedList userList = this.getChildren(); Iterator iter =
	 * userList.iterator(); //对于每一个子 while (iter.hasNext()) { Resource re =
	 * (Resource) iter.next(); //添加组织 childrenUsers.add(re); if(re instanceof
	 * Organization) { //添加组织下的所有用户 childrenUsers.addAll(re.getAllChildrens()); } }
	 * return childrenUsers; }
	 */
	public LinkedList getAllUsers() throws Exception {
		LinkedList result = new LinkedList();
		Set temp = new HashSet();
		// 取得所有孩子
		Iterator iter = this.getChildren();
		while (iter.hasNext()) {
			Object o = iter.next();
			if (o instanceof User) {
				temp.add(o);
			} else if (o instanceof Role) {
				temp.addAll(((Role) o).getUsers());
			} else if (o instanceof Organization) {
				Organization or = (Organization) o;
				temp.addAll(or.getAllUsers());
			}
		}
		result.addAll(temp);
		return result;
	}

	/**
	 * 看是否需要插入
	 * 
	 * @return 是否需要插入
	 */
	protected boolean isShouldInsert() {
		// 如果有action
		Element e = this.component.getElement();
		Iterator iter = ExtendElement.findElements(e, "name", "action")
				.iterator();
		if (iter.hasNext()) {
			// 如果有parentID,并且action的值为"confirm"
			if (parentID != null && !parentID.equals("") && action != null
					&& action.equals("confirm")) {
				return true;
			}
		}
		// 否则,如果有parentID
		else if (parentID != null && !parentID.equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 是否应该更新数据库
	 * 
	 * @return 是否应该更新数据库
	 */
	protected boolean isShouldUpdate() {
		// 如果页面有action
		Element e = this.component.getElement();
		Iterator iter = ExtendElement.findElements(e, "name", "action")
				.iterator();
		if (iter.hasNext()) {
			// 如果action的值不为"confirm"
			if (action == null || !action.equals("confirm")) {
				return false;
			}
		}
		return true;
	}
}